import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, Card, message, Row, Col } from "antd";
import { MobileOutlined, SafetyCertificateOutlined } from "@ant-design/icons";

import { login } from "../../services/auth";

import styles from "./Login.module.scss";
import logoImage from "../../assets/react.svg";

interface LoginForm {
  phone: string;
  verificationCode: string;
}

const Login = () => {
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const navigate = useNavigate();

  const handleLogin = async (values: LoginForm) => {
    setLoading(true);
    try {
      // 这里应该调用实际的登录 API
      const response = await login({
        username: values.phone,
        captcha: values.verificationCode,
      });
      if (response.token) {
        localStorage.setItem("token", response.token);
        message.success("登录成功");
        navigate("/agents");
        setLoading(false);
      } else {
        message.error("登录失败，请检查手机号和验证码");
        setLoading(false);
      }
    } catch (error) {
      message.error("登录失败，请检查手机号和验证码");
      setLoading(false);
    }
  };

  const handleSendVerificationCode = async () => {
    const phone = Form.useForm()[0].getFieldValue("phone");

    if (!phone) {
      message.error("请先输入手机号");
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      message.error("请输入正确的手机号");
      return;
    }

    setSendingCode(true);

    try {
      // 这里应该调用发送验证码的 API
      // await sendVerificationCode(phone);

      // 模拟发送验证码
      message.success("验证码已发送");

      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prevCountdown) => {
          if (prevCountdown <= 1) {
            clearInterval(timer);
            setSendingCode(false);
            return 0;
          }
          return prevCountdown - 1;
        });
      }, 1000);
    } catch (error) {
      message.error("验证码发送失败，请稍后再试");
      setSendingCode(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginBox}>
        <Card className={styles.card}>
          <div className={styles.logoContainer}>
            <img src={logoImage} alt="Logo" className={styles.logo} />
          </div>

          <h1 className={styles.title}>九紫商学AI平台</h1>

          <p className={styles.description}>AI改变人生，助力全国创业女性</p>

          <Form
            name="login"
            initialValues={{ remember: true }}
            onFinish={handleLogin}
            size="large"
            className={styles.form}
          >
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
              ]}
            >
              <Input prefix={<MobileOutlined />} placeholder="手机号" />
            </Form.Item>

            <Form.Item
              name="verificationCode"
              rules={[{ required: true, message: "请输入验证码" }]}
            >
              <Row gutter={8}>
                <Col flex="auto">
                  <Input
                    prefix={<SafetyCertificateOutlined />}
                    placeholder="验证码"
                  />
                </Col>
                <Col>
                  <Button
                    type="primary"
                    onClick={handleSendVerificationCode}
                    disabled={sendingCode}
                    className={styles.codeButton}
                  >
                    {countdown > 0 ? `${countdown}秒后重新获取` : "获取验证码"}
                  </Button>
                </Col>
              </Row>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className={styles.loginButton}
                loading={loading}
                block
              >
                登录 / 注册
              </Button>
            </Form.Item>

            <div className={styles.registerHint}>新用户将自动为您注册账号</div>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default Login;
